package cate.game.util.sensitive;

import cate.game.table.GameTableContext;
import cate.game.util.DebugGameConf;
import easy.java.practice.errorcode.EcException;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class SensitiveWordsTool {

    private List<String> words;

    public void setup(String excelPath, String excelMode) throws Exception {
        if(DebugGameConf.debugExcelLoadDisabled) {
            this.words = new ArrayList<>();
            return;
        }
        GameTableContext gtc = new GameTableContext(excelPath, excelMode);
        List<String> wordsNew = new ArrayList<>();
        File f = gtc.getFile("屏蔽字库.txt");
        if(!f.exists()) {
            throw new EcException("屏蔽字库的配置文件不存在");
        }
        InputStream ips = new FileInputStream(f);
        BufferedReader reader = new BufferedReader(new InputStreamReader(ips));
        String keyword;
        while((keyword=reader.readLine())!=null){
            wordsNew.add(keyword);
        }
        this.words = wordsNew;
    }

    private void loadWords() {
    }

    /** 是否合法 */
    public boolean legal(String origin) {
        if(origin == null) {
            return true;
        }
        loadWords();
        if(words == null || words.isEmpty()) {
            throw new EcException("SW字库加载失败");
        }
        for(String word : words) {
            if(origin.contains(word)) {
                return false;
            }
        }
        return true;
    }

    public String replace(String origin) {
        if(origin == null) {
            return null;
        }
        loadWords();
        if(words == null || words.isEmpty()) {
            return "-sw-err-";
        }
        for(String word : words) {
            if(origin.contains(word)) {
                StringBuilder rpm = new StringBuilder();
                for(int i = 0; i < word.length(); i++) {
                    rpm.append("*");
                }
                origin = origin.replace(word, rpm.toString());
            }
        }
        return origin;
    }
}
